<script lang="ts" setup>
// 作品管理页
import { useRouter } from 'vue-router';
import { ref, computed, inject, onMounted } from 'vue';
import CryptoJS from 'crypto-js';

const router = useRouter();
const axios = inject('axios'); // 注入 axios
const works = ref([]); // 初始化作品数组

const imageBasePath = 'http://localhost:8080/api/images/'; // 定义后端图片API接口路径

// 获取完整的图片 URL
const getImageUrl = (fileName) => {
    console.log("imageURL:", imageBasePath + fileName);
    return fileName ? `${imageBasePath}${fileName}` : '0 (3).jpg'; // 默认图片处理
};

const itemsPerPage = 3; // 每页显示的作品数量
const currentPage = ref(1); // 当前页

const totalPages = computed(() => {
    return Math.ceil(works.value.length / itemsPerPage);
});

const paginatedWorks = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return works.value.slice(start, start + itemsPerPage);
});

// 跳转到新建作品页面的函数
const navigateToNewWork = () => {
    router.push('/staging/newWork');
};

// 解密token
const getToken = () => {
    const encryptedToken = localStorage.getItem('token');
    if (encryptedToken) {
        const secretKey = 'your_secret_key'; // 使用相同的密钥
        const bytes = CryptoJS.AES.decrypt(encryptedToken, secretKey);
        return bytes.toString(CryptoJS.enc.Utf8);
    }
    return null;
};

// 获取作品列表的函数
const fetchWorks = async () => {
    const token = getToken();
    console.log("token:", token);
    try {
        const response = await axios.post('http://localhost:8080/api/getworklistByUID', {}, {
            headers: {
                Authorization: 'Bearer ' + token,
            },
        });

        if (response.data.code === 200) {
            const data = response.data.data;
            // 循环遍历作品以获取剧本标签
            works.value = await Promise.all(data.map(async (work) => {
                const scriptTypes = await fetchScriptTypes(work.wid); // 获取剧本标签
                return {
                    title: work.wname,
                    id: work.wid,
                    wimage: work.wimage,
                    status: work.workScriptState,
                    workWstate: work.workWstate,
                    tag: work.labelIds ? work.labelIds.join(', ') : '无标签', // 标签
                    updateTime: work.wnowdate ? work.wnowdate.split(' ')[0] : '无更新记录', // 更新日期
                    scriptTypes // 添加剧本标签到作品中
                };
            }));
            console.log("works:", JSON.stringify(works.value, null, 2));
        } else {
            console.error('数据获取失败:', response.data.message);
        }
    } catch (error) {
        console.error('请求失败:', error);
    }
};

// 获取剧本标签的函数
const fetchScriptTypes = async (wid) => {
    try {
        const response = await axios.get(`http://localhost:8080/api/getworklabelByWid/${wid}`);
        return response.data.data || []; // 返回剧本标签列表
    } catch (error) {
        console.error('获取剧本标签失败:', error);
        return []; // 出错时返回空数组
    }
};

// 跳转剧本内容编写页面
const goToWrite = (workId) => {
    console.log("workId:", workId);
    router.push({ name: 'Write', params: { id: workId } });
};

// 获取标签类型
const getTagType = (status) => {
    if (status === '锁定或屏蔽') {
        return 'danger';
    }
    return status === '作品正常' ? 'success' : 'info';
};

// 获取标签样式
const getTagStyle = (status) => {
    if (status === '锁定或屏蔽') {
        return { color: 'red' };
    }
    return {};
};

// 跳转到对应页面
const goToPage = (pageType, workId) => {
    if (pageType === 'workSettings') {
        console.log("workId:", workId);
        router.push({ name: 'WorkSetting', params: { id: workId } });
    } else if (pageType === 'contractSettings') {
        router.push({ name: 'ContractSettings', params: { id: workId } });
    }
};

// 在组件挂载时获取数据
onMounted(fetchWorks);
</script>

<template>
    <div class="mystaging">
        <!-- 作品管理 -->
        <div class="mywork">
            <div class="mywork-title">我的作品</div>
            <el-button type="primary" style="margin-left: 1%;" @click="navigateToNewWork">新建作品</el-button>
            <hr style="width: 1100px; border: none; border-top: 1px solid #ccc;">
        </div>
        <div class="mywork-content">
            <el-card v-for="(work, index) in paginatedWorks" :key="index" class="mywork-card">
                <div class="card-link">
                    <img :src="getImageUrl(work.wimage)" alt="作品图片" class="card-image" />
                    <div class="card-body">
                        <div class="card-body-text">
                            <div class="card-body-title">
                                <div class="title-wrapper">
                                    <h3>{{ work.title }}</h3>
                                    <el-tag :type="getTagType(work.status)" class="tag"
                                        :style="getTagStyle(work.status)" style="float: right;font-size: 12px;">
                                        {{ work.status }}
                                    </el-tag>
                                </div>
                            </div>
                            <div>
                                <el-tag type="primary" class="tag">作品标签:
                                    <span>{{ work.scriptTypes.map(scriptType => scriptType.bname).join('、') || '无标签'
                                        }}</span> <!-- 显示剧本标签 -->
                                </el-tag>
                            </div>
                            <div class="card-body-subtitle">
                                <p style="margin-bottom: 1px;">更新时间：{{ work.updateTime }}</p>
                                <div style="margin-bottom: 5px;">
                                    <el-button type="primary" style="float: right; margin-left: 10px;"
                                        @click="goToWrite(work.id)">去写作</el-button>
                                    <el-dropdown placement="bottom">
                                        <el-button> 作品相关
                                            <el-icon style="margin-left: 3px;">
                                                <ArrowDown />
                                            </el-icon>
                                        </el-button>
                                        <template #dropdown>
                                            <el-dropdown-menu>
                                                <el-dropdown-item
                                                    @click="goToPage('workSettings', work.id)">作品设置</el-dropdown-item>
                                                <el-dropdown-item
                                                    @click="goToPage('contractSettings', work.id)">合同设置</el-dropdown-item>
                                            </el-dropdown-menu>
                                        </template>
                                    </el-dropdown>
                                    <el-button type="" style="margin-left: auto; margin-left: 10px;">
                                        {{ work.workWstate }}
                                    </el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </el-card>
        </div>
        <!-- 分页控制 -->
        <div class="pagination">
            <el-button :disabled="currentPage === 1" @click="currentPage--">上一页</el-button>
            <span>第 {{ currentPage }} 页</span>
            <el-button :disabled="currentPage === totalPages" @click="currentPage++">下一页</el-button>
        </div>
    </div>
</template>

<style scoped>
.mystaging {
    width: 90%;
    background-color: rgb(255, 255, 255);
}

.mywork {
    margin-left: 7%;
    height: 50px;
    width: 100%;
    margin-bottom: 30px;
}

.mywork-title {
    display: inline-flex;
    align-items: center;
    justify-content: flex-end;
    height: 50px;
    font-size: 24px;
}

.mywork-content {
    width: 100%;
    height: 550px;
    margin-left: 7%;
}

.mywork-card {
    height: 180px;
    margin-bottom: 5px;
}

.card-link {
    display: flex;
    text-decoration: none;
}

.card-image {
    width: 130px;
    height: 155px;
    margin-right: 16px;
}

.card-body {
    flex: 1;
}

.card-body-title {
    margin: 0;
}

.title-wrapper {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 35px;
}

h3 {
    height: 35px;
    color: #000000;
    text-align: center;
    line-height: 35px;
    margin: 0;
}

.tag {
    margin-left: auto;
}

.card-body-subtitle {
    margin-top: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.pagination {
    margin-top: 5px;
    display: flex;
    justify-content: center;
}

.pagination span {
    margin: 0 10px;
}
</style>
